package com.jxt.myapp.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jxt.myapp.domain.Group;
import com.jxt.myapp.domain.Menu;
import com.jxt.myapp.domain.jqgrid.JqGridParameter;
import com.jxt.myapp.domain.json.CustomGenericResponse;
import com.jxt.myapp.domain.json.CustomGroupResponse;
import com.jxt.myapp.service.IPermissionsService;
import com.jxt.myapp.utils.DateUtils;
import com.jxt.myapp.utils.PaginationUtils;

@Controller
@RequestMapping("/group")
public class GroupController {

	@Resource(name = "permissionsService")
	private IPermissionsService permissionsService;

	private static final Logger logger = LoggerFactory
			.getLogger(GroupController.class);

	/**
	 * 获得所有的权限组(Group)
	 * 
	 * @param page
	 * @param rows
	 * @param sidx
	 * @param sord
	 * @param isSearch
	 * @param filters
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public @ResponseBody
	CustomGroupResponse getAllGroup(@RequestParam("page") String page,
			@RequestParam("rows") String rows,
			@RequestParam("sidx") String sidx,
			@RequestParam("sord") String sord,
			@RequestParam("_search") Boolean isSearch,
			@RequestParam(value = "filters", required = false) String filters) {

		logger.info("GetAllGroup Method!");

		JqGridParameter jqGridParameter = new JqGridParameter();

		jqGridParameter.setPage(Integer.parseInt(page));
		jqGridParameter.setRows(Integer.parseInt(rows));
		jqGridParameter.setSidx(sidx);
		jqGridParameter.setSord(sord);
		jqGridParameter.setFilters(filters);

		long records = 0;

		List<Group> groups = Collections.emptyList();

		if (StringUtils.isNotEmpty(filters)) {
			groups = permissionsService.getAllGroupByParameter(jqGridParameter);
			records = permissionsService
					.getAllGroupByParameterCount(jqGridParameter);
		} else {
			groups = permissionsService.getAllGroup(jqGridParameter);
			records = permissionsService.getAllGroupCount(jqGridParameter);
		}

		long total = PaginationUtils
				.getPageCount(records, Long.parseLong(rows));

		CustomGroupResponse response = new CustomGroupResponse();

		response.setRows(groups);

		response.setRecords(String.valueOf(records));

		response.setPage(page);

		response.setTotal(String.valueOf(total));

		return response;

	}
	

	/**
	 * 根据ID获得对应的Group和Menu信息,返回到指定页面上
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public ModelAndView getGroupMeunById(@PathVariable("id") String id,
			Model model) {

		// 根据ID获得该GroupId下所拥有的权限菜单.
		List<String> list = permissionsService.getMenuByGroup(id);

		// 根据ID获得所有的权限组信息.
		Group group = permissionsService.getGroupById(id);

		// 查询得到所有的权限菜单传送到页面显示.
		List<Menu> menuList = permissionsService.getAllMenu();

		model.addAttribute("menuList", menuList);
		model.addAttribute("id", id);

		Map<String, String> map = new HashMap<String, String>();

		for (int i = 0; i < list.size(); i++) {
			map.put(list.get(i), list.get(i));
		}
		group.setMenus(map);

		return new ModelAndView("editGroup", "command", group);

	}

	/**
	 * 对Group进行修改
	 * 
	 * @param id
	 * @param name
	 * @param remark
	 * @param state
	 * @param menus
	 * @return
	 */
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
	public String editGroup(@ModelAttribute("Group") Group group,
			@PathVariable("id") String id) {
		logger.info("Edit Group Method!");
		logger.info("  id:" + id);
		group.setId(id);

		List<Object> list = new ArrayList<Object>();

		for (Map.Entry<String, String> map : group.getMenus().entrySet()) {
			if (map.getValue() != null) {
				list.add(map.getValue());
			}
		}
		String[] menus = list.toArray(new String[] {});
		int success = permissionsService.updateGroup(group, menus);
		logger.info("edit int:"+success);
		return "group";

	}

	/**
	 * 跳转到addgroup页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/toAddPage", method = RequestMethod.GET)
	public ModelAndView toAddGroupPage(Group group,Model model) {
		// 查询得到所有的权限菜单传送到页面显示.
		List<Menu> menuList = permissionsService.getAllMenu();
		model.addAttribute("menuList", menuList);
		return new ModelAndView("addGroup", "command", new Group());
	}

	/**
	 * 添加Group和Menu
	 * 
	 * @param group
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String addGroup(@ModelAttribute("Group") Group group) {
		logger.info("Add Group Method!");

		logger.info("group Name:" + group.getName());
		logger.info("group Remark:" + group.getRemark());
		logger.info("group state:" + group.getState());
		logger.info("group id:" + group.getId());

		
		group.setCreateTime(DateUtils.nowTime());
		String uuid = UUID.randomUUID().toString();
		group.setId(uuid);

		List<Object> list = new ArrayList<Object>();

		for (Map.Entry<String, String> map : group.getMenus().entrySet()) {
			if (map.getValue() != null) {
				list.add(map.getValue());
			}
		}
		String[] menus = list.toArray(new String[] {});

		int success = permissionsService.addGroup(group, menus);
		logger.info("add int:"+success);

		return "group";
	}

	/**
	 * 注销Group
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody
	CustomGenericResponse deleteMoreGroup(@RequestParam("id") String[] id) {
		logger.info("Delete Group Method!");
		final int DELETE_STATE = 0;
		List<Group> groupList = new ArrayList<Group>();

		for (int i = 0; i < id.length; i++) {
			Group group = new Group();
			group.setId(id[i]);
			group.setState(DELETE_STATE);
			group.setWithdrawTime(DateUtils.nowTime());
			groupList.add(group);
		}
		int[] success = permissionsService.deleteGroup(groupList);

		CustomGenericResponse response = new CustomGenericResponse();

		boolean isSuccess = true;

		// 如果返回为-1,则表示操作失败.
		for (int i = 0; i < success.length; i++) {
			if (success[i] == -1) {
				isSuccess = false;
			}
		}
		if (isSuccess) {
			response.setSuccess(true);
			response.setMessage("批量删除成功!");
		} else {
			response.setSuccess(false);
			response.setMessage("批量删除失败!");
		}
		return response;

	}


}
